import axios from 'axios';

const request = axios.create({
    baseURL: '/pokemon-battle', // 与 Vite 代理路径匹配
    timeout: 10000, // 10秒超时
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 可在此添加 token 或其他头部信息
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(
    response => {
        return response.data;
    },
    error => {
        if (error.response) {
            const { status, data } = error.response;
            if (status === 400) return Promise.reject(new Error('Bad Request: ' + (data.error || '参数错误')));
            if (status === 404) return Promise.reject(new Error('Not Found: ' + (data.error || '资源不存在')));
            if (status === 500) return Promise.reject(new Error('Server Error: ' + (data.error || '服务器错误')));
        }
        return Promise.reject(new Error('Network Error: ' + error.message));
    }
);

export default {
    get(url, params = {}) {
        return request.get(url, { params });
    },
    post(url, data = {}) {
        return request.post(url, data);
    }
};